<?php

/**
 * Propel Behavior for create and manage uploaded photo
 * 
 * @package    phImageBuilder
 * @subpackage ImageBuilderBehavior
 * @author     Samusevich Alexander <archer@fishartis.com>
 * @version    1.0 2011-11-14 14:27 archer
 */
class ImageBuilderBehavior
{
    /**
    * Get photo path by format
    * 
    * @param mixed $oObject
    * @param string $sFormat
    */
    public function getPhotoPath( $oObject, $sFormat = null )
    {               
        // Load model config               
        $this->loadModelData( $oObject );
        
        // Prepare getter name
        $sImgMethod = "get" . sfInflector::camelize( $this->sImageField );
                    
        $sExt = '';
        
        if( $sFormat !== null )
        {      
            // Check thumb format avaibility
            // Read all photo preview          
            $aThumbs = sfConfig::get('app_'.$this->namespace.'_thumbs');
            
            if( !$aThumbs || !isset( $aThumbs[$sFormat]) )
            {
                // Format not found
                throw new sfException( 'Invalid image format: ' . $sFormat );
            }
            
            // Read format extension
            $sExt = (isset($aThumbs[$sFormat]['ext']) && $aThumbs[$sFormat]['ext']) ? $aThumbs[$sFormat]['ext'] : '.' . $sFormat;    
        }
                                                                         
        if( file_exists( $this->sUplDir . $oObject->$sImgMethod() . $sExt ) )
        {
            return $this->sUplUrl . $oObject->$sImgMethod() . $sExt;    
        } 
        
        // Generate url for empty image 
        $sEmptyImage = sfConfig::get( 'app_empty_image_tpl' );
        $sEmptyImage = ($sEmptyImage) ? $sEmptyImage : "%image_folder%_emptyimage%ext%.png";
        
        return strtr( $sEmptyImage, array( '%image_folder%' => $this->sUplUrl, '%ext%' => $sExt ) );
    }
        
    /**
    * Create photo preview after uploading
    * 
    * @param mixed $oObject
    * @param PropelPDO $con
    */
    public function postSave( $oObject, PropelPDO $con = null )
    {   
        // Load model config
        $this->loadModelData( $oObject );
        
        // Prepare getter name
        $sImgMethod = "get" . sfInflector::camelize( $this->sImageField );
        
        if( $oObject->$sImgMethod() )
        {
            // Read all photo preview          
            $aThumbs = sfConfig::get('app_'.$this->namespace.'_thumbs');
            
            foreach( $aThumbs as $sThumbName => $aProperties )
            {
                // Check thumb extension
                if( !isset($aProperties['ext']) || !$aProperties['ext'])
                {
                    $aProperties['ext'] = '.' . $sThumbName;
                }
                
                // Disable thumb rewriting
                if( !file_exists( $this->sUplDir . $oObject->$sImgMethod() . $aProperties['ext'] ) )
                {
                    $this->createThumb( $oObject, $sThumbName );    
                }
            }
        }
        
        return true;
    }   
    
    /**
    * Create thumb by configuration 
    * 
    * @param string $sThumbName - configuration name
    * @param integer $iStartX   - offset position (middle by default)
    * @param integer $iStartY   - offset position (middle by default)
    */
    public function createThumb( $oObject, $sThumbName, $iStartX = -1, $iStartY = -1, $iScale = 1 )
    {
        // Load model config
        $this->loadModelData( $oObject );
        
        // Prepare getter name
        $sImgMethod = "get" . sfInflector::camelize( $this->sImageField );
        
        // Configure image decorator
        ImageCropDecorator::clearProperties();
        // Set upload path
        ImageCropDecorator::setSourceDir( $this->sUplDir );
        ImageCropDecorator::setDestDir( $this->sUplDir );
        
        // Read preview extension (e.g. .small)
        $sExt = sfConfig::get('app_'.$this->namespace.'_image_ext');
                
        // Read configuration
        $this->aThumbs = sfConfig::get('app_'.$this->namespace.'_thumbs');
        $aConfiguration = $this->aThumbs[$sThumbName];
        
        // Configure thumb
        ImageCropDecorator::addImageProperty
        (
            array(  'name'      => $oObject->$sImgMethod(),
                    'ext'       => $sExt,
                    'width'     => (isset($aConfiguration['width']))  ? $aConfiguration['width']  : '9999',
                    'height'    => (isset($aConfiguration['height'])) ? $aConfiguration['height'] : '9999',
                    'method'    => (isset($aConfiguration['method'])) ? $aConfiguration['method'] : '',
                    'pfx'       => (isset($aConfiguration['ext']) && $aConfiguration['ext']) ? $aConfiguration['ext'] : '.' . $sThumbName,
                    'x'         => $iStartX,
                    'y'         => $iStartY,
                    'scale'     => $iScale,
                    'copyright' => (isset($aConfiguration['copyright'])) ? $aConfiguration['copyright'] : null,
					'rights'    => (isset($aConfiguration['rights'])) ? $aConfiguration['rights'] : null,
					'owner'     => (isset($aConfiguration['owner'])) ? $aConfiguration['owner'] : null,
            )
        );   
                               
        // Create thumb        
        ImageCropDecorator::create( $oObject->$sImgMethod() );    
    }
    
    /**
    * Remove photo and all preview before deleting
    * 
    * @param mixed $oObject
    * @param PropelPDO $con
    */
    public function postDelete( $oObject, PropelPDO $con = null )
    {
        // Load model config
        $this->loadModelData( $oObject );
        
        // Prepare getter name
        $sImgMethod = "get" . sfInflector::camelize( $this->sImageField );
        
        // Read all photo preview
        $aThumbs = sfConfig::get('app_'.$this->namespace.'_thumbs');
        $aThumbs[] = array( 'ext' => '' );
            
        foreach( $aThumbs as $sThumbName => $aProperties )
        {
            // Check thumb extension
            if( !isset($aProperties['ext']))
            {
                $aProperties['ext'] = '.' . $sThumbName;
            }
            
            // Delete preview
            @unlink( $this->sUplDir . $oObject->$sImgMethod() . $aProperties['ext'] );
        } 
        
        return true;
    }
    
    /**
    * Decode model object and read config data
    * 
    * @param mixed $oObject - propel object
    */
    private function loadModelData( $oObject )
    {                               
        $this->namespace = sfInflector::tableize( get_class( $oObject ) );
        
        $this->sImageField = sfConfig::get('app_'.$this->namespace.'_image_field');
        $this->sImageField = ($this->sImageField) ? $this->sImageField : "photo";
        
        $this->sImgFolder = sfConfig::get( 'app_'.$this->namespace.'_image_folder', $this->namespace );
        
        $this->sUplUrl = '/uploads' . '/' . trim( $this->sImgFolder, '/' ) . '/';
        $this->sUplDir = sfConfig::get('sf_upload_dir') . '/' . trim( $this->sImgFolder, '/' ) . '/';
        
        if( !file_exists( $this->sUplDir ) )
        {
            @mkdir( $this->sUplDir, 0777, true );
            @chmod( $this->sUplDir, 0777 );
        }
    }
}